package com.ok.common.api;


import android.annotation.SuppressLint
import android.content.Context
import android.util.Log
import com.cszy.mfjx.lib_hlyj_base.BuildConfig
import com.github.gzuliyujiang.oaid.DeviceID
import com.github.gzuliyujiang.oaid.DeviceIdentifier
import com.github.gzuliyujiang.oaid.IGetter
import com.hlyj.http.base.tool.lib_hlyj_base.BaseApplication
import com.hlyj.http.base.tool.lib_hlyj_base.Constants
import com.hlyj.http.base.tool.lib_hlyj_base.bean.BaseResult
import com.hlyj.http.base.tool.lib_hlyj_base.bean.GetadswitchBean
import com.hlyj.http.base.tool.lib_hlyj_base.bean.GetadswitchResultBean
import com.hlyj.http.base.tool.lib_hlyj_base.bean.HuaFeiSearchBean
import com.hlyj.http.base.tool.lib_hlyj_base.bean.HuaFeiSearchResultBean
import com.hlyj.http.base.tool.lib_hlyj_base.bean.UpdateuseridBean
import com.hlyj.http.base.tool.lib_hlyj_base.bean.music.MusicListBean
import com.hlyj.http.base.tool.lib_hlyj_base.camera.LoginBean
import com.hlyj.http.base.tool.lib_hlyj_base.camera.LoginResultBean
import com.hlyj.http.base.tool.lib_hlyj_base.camera.OrderBean
import com.hlyj.http.base.tool.lib_hlyj_base.camera.ShopInfoBean
import com.hlyj.http.base.tool.lib_hlyj_base.camera.UserInfoResultBean
import com.hlyj.http.base.tool.lib_hlyj_base.net.ApiCallback
import com.hlyj.http.base.tool.lib_hlyj_base.net.AppRiskConfigBean
import com.hlyj.http.base.tool.lib_hlyj_base.net.BaseCallback
import com.hlyj.http.base.tool.lib_hlyj_base.net.MeApi
import com.hlyj.http.base.tool.lib_hlyj_base.qrcode.BaseResult_Qrcode
import com.hlyj.http.base.tool.lib_hlyj_base.qrcode.QrResultBean
import com.hlyj.http.base.tool.lib_hlyj_base.utils.BaseAppConstans
import com.hlyj.http.base.tool.lib_hlyj_base.utils.BaseModuleSpUtils
import com.hlyj.http.base.tool.lib_hlyj_base.utils.DeviceModeUtil
import com.hlyj.http.base.tool.lib_hlyj_base.utils.MMKVUtils
import com.hlyj.http.base.tool.lib_hlyj_base.utils.ProxyChecker
import com.hlyj.http.base.tool.lib_hlyj_base.utils.RiskManagementUtil
import com.hlyj.http.base.tool.lib_hlyj_base.utils.VpnDetector
import com.hlyj.http.base.tool.lib_hlyj_base.weather.HolidayResultBean
import com.hlyj.http.base.tool.lib_hlyj_base.weather.WeatherResultBean
import com.hlyj.http.base.tool.lib_hlyj_base.weather.WeatherResultBeanFor40Day
import com.hnyyac.ad.mds.utils.BaseAdConstants
import com.hnyyac.ad.mds.utils.BaseAdSpUtils
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.util.concurrent.atomic.AtomicInteger


object GlobalApi {
       private var api: MeApi = HttpHelper.api
       private var api_logSend: MeApi = HttpHelper_logSend.api
       private var api_qrcode: MeApi = HttpHelper_qrcode.api  //二维码查价
       private var api_weather: MeApi = HttpHelper_weather.api  //二维码查价
       private var api_holiday: MeApi = HttpHelper_canlendar.api  //黄历日历
    /**
     * 获取广告开关
     */
    @SuppressLint("SuspiciousIndentation")
    fun getadswitch (callback: ApiCallback<BaseResult<GetadswitchResultBean?>?>) {
        var resultBean = MMKVUtils.getObject(Constants.initSwitchResultBean, GetadswitchResultBean::class.java)
        var adSwitch = BaseModuleSpUtils.getInstance().getString(Constants.NATIVEADSWITCH) //本地广告缓存开关
        var privateSwitch = BaseModuleSpUtils.getInstance().getString(Constants.NATIVEPRIVACYSWITCH) //本地隐私缓存开关
        var oaid= BaseModuleSpUtils.getInstance().getString(Constants.OAID)
        var list_black=   BaseModuleSpUtils.getInstance().getStringList(BaseAppConstans.BLACK_LIST)
        //Log.e("qin","传过去的黑名单列表"+list_black)
        var list_white=   BaseModuleSpUtils.getInstance().getStringList(BaseAppConstans.WHITE_LIST)
       // Log.e("qin","传过去的白名单列表"+list_white)
        val reportADSwitchbean =
            GetadswitchBean(
                 resultBean?.hardwareInfo?:"",
                System.currentTimeMillis().toString(),
                adSwitch,
                privateSwitch,
                resultBean?.isBlacklist?:"",
                resultBean?.isMonitor?:"",
                ProxyChecker.checkProxyStatus(BaseApplication.instance),
                DeviceModeUtil.getInstance().isCharging(BaseApplication.instance),
                DeviceModeUtil.getInstance().getChargingType(BaseApplication.instance),
                RiskManagementUtil.isRooted(),
                DeviceModeUtil.getInstance().cpuName,
                RiskManagementUtil.isSimCardInserted(BaseApplication.instance),
                DeviceModeUtil.getInstance().getBatteryLevel(BaseApplication.instance),
                VpnDetector.isProxyActive(BaseApplication.instance),
                oaid,
                list_black,
                list_white
            )
      // Log.e("qin","--------参数"+reportADSwitchbean.toString())
        api.getAdSwitch(reportADSwitchbean)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : BaseCallback<BaseResult<GetadswitchResultBean?>?>() {
                override fun onSuccess(model: BaseResult<GetadswitchResultBean?>?) {
                     if (model?.status == 200) {
                         BaseModuleSpUtils.getInstance().putString(Constants.HARDWAREINFO, model?.data?.hardwareInfo?:"")
                         BaseModuleSpUtils.getInstance().putString(Constants.PRIVACYID, model?.data?.privacyId?:"")
                         BaseAdSpUtils.getInstance().putString(BaseAdConstants.CHANNEL_ID_GET, model?.data?.channel?:"")//ad包存入渠道
                         callback.onSuccess(model)
                         Log.e("qin","--------onSuccess"+model?.data.toString())
                    }else{
                       // Log.e("qin","--------onFailure"+model?.status)
                        callback.onFailure(model?.msg.toString())
                    }

                }

                override fun onFailure(msg: String) {
                  //  Log.e("qin","--------onFailure"+msg)
                    callback.onFailure(msg)
                }

                override fun onFinish() {
                    Log.e("qin","--------onFinish")
                    callback.onFinish()
                }
            })
    }


    /**
     * 更新广告开关
     * @param context
     * @param callback
     * @param oaid
     */
    @SuppressLint("SuspiciousIndentation")
    fun updateUserInfo (context: Context,callback: ApiCallback<BaseResult<GetadswitchResultBean?>?>) {
        var oaid= BaseModuleSpUtils.getInstance().getString(Constants.OAID)
         if (oaid.isNotEmpty())return //如果缓存里面有oaid  不执行后面的逻辑
          DeviceIdentifier.register(BaseApplication.instance);
        val maxRetries = 3
        val retryCount = AtomicInteger(0)
        fun getOAIDWithRetry() {
            DeviceID.getOAID(context, object : IGetter {
                override fun onOAIDGetComplete(result: String) {
                    BaseModuleSpUtils.getInstance().putString(Constants.OAID, result)
                    //Log.d("qin", "oiad----------------$result")
                    update( context,callback, result)
                }

                override fun onOAIDGetError(error: Exception) {
                   // Log.d("qin", "onOAIDGetErro: ${error.message}")
                    if (retryCount.incrementAndGet() < maxRetries) {
                        GlobalScope.launch {
                            delay(2000) // 延迟 2 秒
                            withContext(Dispatchers.Main) {
                                getOAIDWithRetry()
                            }
                        }
                    } else {
                        // 可以在这里添加处理最终失败的逻辑，例如调用 callback 的失败方法
                        callback.onFailure("Failed to get OAID after $maxRetries retries.")
                        update( context,callback, "")//三次都没拿到则传其它信息
                    }
                }
            })
        }

        // 使用协程在 IO 线程中启动获取 OAID 的操作
        GlobalScope.launch(Dispatchers.IO) {
            getOAIDWithRetry()
        }

    }

    fun  update(context: Context,callback: ApiCallback<BaseResult<GetadswitchResultBean?>?>,oaid_update :String){
        var resultBean = MMKVUtils.getObject(Constants.initSwitchResultBean, GetadswitchResultBean::class.java)

        val uodatetADSwitchbean =
            UpdateuseridBean(
                  oaid_update,
                  resultBean?.hardwareInfo?:"",
                   BuildConfig.APPCODE,
                   DeviceModeUtil.getInstance().getAndroidId(context),
                   DeviceModeUtil.getInstance().getIMEI(context)
            )
        Log.e("qin","update--------参数"+uodatetADSwitchbean.toString())
        api.updateUserIdentity(uodatetADSwitchbean)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : BaseCallback<BaseResult<GetadswitchResultBean?>?>() {
                override fun onSuccess(model: BaseResult<GetadswitchResultBean?>?) {
                    if (model?.status == 200) {
                        callback.onSuccess(model)
                      //  Log.e("qin","Update--------onSuccess"+model?.data.toString())
                    }else{
                       // Log.e("qin","Update--------onFailure"+model?.status)
                        callback.onFailure(model?.msg.toString())
                    }

                }

                override fun onFailure(msg: String) {
                  //  Log.e("qin","--------onFailure"+msg)
                    callback.onFailure(msg)
                }

                override fun onFinish() {
                    //Log.e("qin","--------onFinish")
                    callback.onFinish()
                }
            })
    }

    /**
     * 日志上报接口
     * @param content 日志内容列表，每个元素是Map<String, String>格式的日志数据
     * @param callback 回调接口
     */
    fun sendLog(content: List<Map<String, Any?>>) {
        val processedLogs = content.map { item ->
            mutableMapOf<String, Any>().apply {
                val nonNullItem = item.filterValues { it != null }

                // 确保必需字段
                require(item["type"] != null) { "type is required" }
                require(item["seq"] != null) { "seq is required" }
                // 添加所有非空字段
                putAll(item.filterValues { it != null } as Map<String, Any>)
                // 转换 seq 为 String
                put("seq", item["seq"].toString())
            }
        }
        Log.e("qin", "--------logSend logParams: $processedLogs")
        // 2. 调用接口
        api_logSend.logSend(processedLogs)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : BaseCallback<String>() {
                override fun onSuccess(model: String) {
                    Log.e("qin", "--------logSend onSuccess: $model")
                    val seqNum: Int = BaseModuleSpUtils.getInstance().getInt(Constants.SEQ, 0)
                    BaseModuleSpUtils.getInstance().putInt(Constants.SEQ, seqNum + 1)


                }

                override fun onFailure(msg: String) {
                    Log.e("qin", "--------logSend onFailure: $msg")

                }

                override fun onFinish() {
                    Log.e("qin", "--------logSend onFinish")

                }
            })
    }
    /**
     * 获取应用黑白名单配置
     */
    fun getAppRiskConfig(callback: ApiCallback<BaseResult<AppRiskConfigBean?>?>) {
        api.getAppRiskConfig()
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : BaseCallback<BaseResult<AppRiskConfigBean?>?>() {
                override fun onSuccess(model: BaseResult<AppRiskConfigBean?>?) {
                    if (model?.status == 200) {
                        callback.onSuccess(model)
                    } else {
                        callback.onFailure(model?.msg ?: "Error")
                    }
                }

                override fun onFailure(msg: String) {
                    callback.onFailure(msg)
                }

                override fun onFinish() {
                    callback.onFinish()
                }
            })
    }
    /**
     * 话费查询接口
     * @param huaFeiSearchBean 请求体
     * @param callback 回调接口
     */
    fun getHuaFeiSeachResult (huaFeiSearchBean: HuaFeiSearchBean,callback: ApiCallback<BaseResult<HuaFeiSearchResultBean?>?>){
       api.HuafeiSeach(huaFeiSearchBean)
           .subscribeOn(Schedulers.io())
           .observeOn(AndroidSchedulers.mainThread())
           .subscribe(object : BaseCallback<BaseResult<HuaFeiSearchResultBean?>?>() {
               override fun onSuccess(model: BaseResult<HuaFeiSearchResultBean?>?) {
                   if (model?.status == 200) {
                       callback.onSuccess(model)

                   }else{
                       // Log.e("qin","--------onFailure"+model?.status)
                       callback.onFailure(model?.msg.toString())
                   }

               }

               override fun onFailure(msg: String) {
                   //  Log.e("qin","--------onFailure"+msg)
                   callback.onFailure(msg)
               }

               override fun onFinish() {
                   Log.e("qin","--------onFinish")
                   callback.onFinish()
               }
           })
    }
    /**
     * 获取音乐列表
     * @param huaFeiSearchBean 请求体
     * @param callback 回调接口
     */
    fun getMusicList (category: String,callback: ApiCallback<BaseResult<List<MusicListBean?>?>>){
        api.getMusicList(category)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : BaseCallback<BaseResult<List<MusicListBean?>?>?>() {
                override fun onSuccess(model: BaseResult<List<MusicListBean?>?>?) {
                    if (model?.status == 200) {
                      //  Log.e("qin","--------getMusicList"+model?.data.toString())
                        callback.onSuccess(model)

                    }else{
                      //   Log.e("qin","--------onFailureget+MusicList"+model?.status)
                        callback.onFailure(model?.msg.toString())
                    }

                }

                override fun onFailure(msg: String) {
                    //  Log.e("qin","--------onFailure"+msg)
                    callback.onFailure(msg)
                }

                override fun onFinish() {
                   // Log.e("qin","--------onFinish")
                    callback.onFinish()
                }
            })
    }
    /**
     * 获取二维码商品接口
     * @param huaFeiSearchBean 请求体
     * @param callback 回调接口
     */
    fun getShopList (barcode : String,callback: ApiCallback<BaseResult_Qrcode<QrResultBean?>>){
        val appCode = "8c8a63d0e151465a8dcce3a7a9be0a43" // 替换为你的实际AppCode

        api_qrcode.getShopList(appCode,barcode)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : BaseCallback<BaseResult_Qrcode<QrResultBean?>?>() {
                override fun onSuccess(model: BaseResult_Qrcode<QrResultBean?>?) {
                    Log.e("qin","--------onSuccess"+model?.status)
                    if (model?.status == "0") {
                          Log.e("qin","--------getMusicList"+model?.data.toString())
                        callback.onSuccess(model)

                    }else{
                        //   Log.e("qin","--------onFailureget+MusicList"+model?.status)
                        callback.onFailure(model?.msg.toString())
                    }

                }

                override fun onFailure(msg: String) {
                    //  Log.e("qin","--------onFailure"+msg)
                    callback.onFailure(msg)
                }

                override fun onFinish() {
                    // Log.e("qin","--------onFinish")
                    callback.onFinish()
                }
            })
    }

    /**
     * 获取二24小时天气接口
     * @param city 城市
     * @param callback 回调接口
     */
    fun get24HoursWeather(city : String,callback: ApiCallback<WeatherResultBean?>){
          api_weather.get24hoursWeather(BaseAppConstans.Weather_APPID,BaseAppConstans.Weather_APPSecret,city,1)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : BaseCallback<WeatherResultBean?>() {
                override fun onSuccess(model: WeatherResultBean?) {
                    Log.e("qin","--------onSuccess"+model?.toString())
                    if (model == null ||
                        (model.city == null && model.wea == null && model.tem == null)) {
                        // 数据无效，走失败回调
                        callback.onFailure("天气数据无效")
                    } else {
                        // 数据有效
                        callback.onSuccess(model)
                    }


                }

                override fun onFailure(msg: String) {
                    //  Log.e("qin","--------onFailure"+msg)
                    callback.onFailure(msg)
                }

                override fun onFinish() {
                    // Log.e("qin","--------onFinish")
                    callback.onFinish()
                }
            })
    }

    /**
     * 获取40天天气接口
     * @param city 城市
     * @param callback 回调接口
     */
    fun get40DayWeather(city : String,callback: ApiCallback<WeatherResultBeanFor40Day?>){
        api_weather.get40DayWeather(1,"v31",BaseAppConstans.Weather_APPID,BaseAppConstans.Weather_APPSecret,city)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : BaseCallback<WeatherResultBeanFor40Day?>() {
                override fun onSuccess(model: WeatherResultBeanFor40Day?) {
                    Log.e("qin","--------onSuccess"+model?.toString())
                    if (model == null ||
                        (model.city == null && model.city == null && model.cityid == null)) {
                        // 数据无效，走失败回调
                        callback.onFailure("天气数据无效")
                    } else {
                        // 数据有效
                        callback.onSuccess(model)
                    }


                }

                override fun onFailure(msg: String) {
                    //  Log.e("qin","--------onFailure"+msg)
                    callback.onFailure(msg)
                }

                override fun onFinish() {
                    // Log.e("qin","--------onFinish")
                    callback.onFinish()
                }
            })
    }

    /**
     * 获取应用黑白名单配置
     */
    fun getHoliday(date: String,callback: ApiCallback<BaseResult<HolidayResultBean?>?>) {
        api_holiday.getCurrentHoliday(date,false,BaseAppConstans.Holiday_APPID,BaseAppConstans.Holiday_APPSecret)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : BaseCallback<BaseResult<HolidayResultBean?>?>() {
                override fun onSuccess(model: BaseResult<HolidayResultBean?>?) {
                    if (model?.status == 1) {
                        callback.onSuccess(model)
                    } else {
                        callback.onFailure(model?.msg ?: "Error")
                    }
                }

                override fun onFailure(msg: String) {
                    callback.onFailure(msg)
                }

                override fun onFinish() {
                    callback.onFinish()
                }
            })
    }
    /**
     * 获取短信验证码登录接口
     * @param phone 电话号码
     * @param callback 回调接口
     */
    fun getVerificationCode (phone: String,callback: ApiCallback<BaseResult<Void?>?>){
        api.getVerificationCode(phone)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : BaseCallback<BaseResult<Void?>?>() {
                override fun onSuccess(model: BaseResult<Void?>?) {
                    if (model?.status == 200) {
                        callback.onSuccess(model)

                    }else{
                        // Log.e("qin","--------onFailure"+model?.status)
                        callback.onFailure(model?.msg.toString())
                    }

                }

                override fun onFailure(msg: String) {
                    //  Log.e("qin","--------onFailure"+msg)
                    callback.onFailure(msg)
                }

                override fun onFinish() {
                    Log.e("qin","--------onFinish")
                    callback.onFinish()
                }
            })
    }


    /**
     * 登录接口
     * @param phone 电话号码
     * @param callback 回调接口
     */
    fun login (loginBean: LoginBean,callback: ApiCallback<BaseResult<LoginResultBean?>?>){
        api.login(loginBean)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : BaseCallback<BaseResult<LoginResultBean?>?>() {
                override fun onSuccess(model: BaseResult<LoginResultBean?>?) {
                    if (model?.status == 200) {
                        callback.onSuccess(model)

                    }else{
                        // Log.e("qin","--------onFailure"+model?.status)
                        callback.onFailure(model?.msg.toString())
                    }

                }

                override fun onFailure(msg: String) {
                    //  Log.e("qin","--------onFailure"+msg)
                    callback.onFailure(msg)
                }

                override fun onFinish() {
                    Log.e("qin","--------onFinish")
                    callback.onFinish()
                }
            })
    }

    /**
     * 获取商品信息列表
     * @param huaFeiSearchBean 请求体
     * @param callback 回调接口
     */
    fun getShopInfoList (callback: ApiCallback<BaseResult<List<ShopInfoBean?>?>>){
        api.getShopList()
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : BaseCallback<BaseResult<List<ShopInfoBean?>?>?>() {
                override fun onSuccess(model: BaseResult<List<ShopInfoBean?>?>?) {
                    if (model?.status == 200) {
                        //  Log.e("qin","--------getMusicList"+model?.data.toString())
                        callback.onSuccess(model)

                    }else{
                        //   Log.e("qin","--------onFailureget+MusicList"+model?.status)
                        callback.onFailure(model?.msg.toString())
                    }

                }

                override fun onFailure(msg: String) {
                    //  Log.e("qin","--------onFailure"+msg)
                    callback.onFailure(msg)
                }

                override fun onFinish() {
                    // Log.e("qin","--------onFinish")
                    callback.onFinish()
                }
            })
    }

    /**
     * 获取用户信息接口
     * @param Authorization token
     * @param callback 回调接口
     */
    fun getUserInfo (token: String,callback: ApiCallback<BaseResult<UserInfoResultBean?>?>){
        api.getUserInfo(token)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : BaseCallback<BaseResult<UserInfoResultBean?>?>() {
                override fun onSuccess(model: BaseResult<UserInfoResultBean?>?) {
                    if (model?.status == 200) {
                        callback.onSuccess(model)

                    }else{
                        // Log.e("qin","--------onFailure"+model?.status)
                        callback.onFailure(model?.msg.toString())
                    }

                }

                override fun onFailure(msg: String) {
                    //  Log.e("qin","--------onFailure"+msg)
                    callback.onFailure(msg)
                }

                override fun onFinish() {
                    Log.e("qin","--------onFinish")
                    callback.onFinish()
                }
            })
    }


    /**
     * 创建订单接口
     * @param Authorization token
     * @param callback 回调接口
     */
    fun createPayment (token: String,orderBean:OrderBean,callback: ApiCallback<BaseResult<Void?>?>){
        api.createPayment(token,orderBean)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : BaseCallback<BaseResult<Void?>?>() {
                override fun onSuccess(model: BaseResult<Void?>?) {
                    if (model?.status == 200) {
                        callback.onSuccess(model)

                    }else{
                        // Log.e("qin","--------onFailure"+model?.status)
                        callback.onFailure(model?.msg.toString())
                    }

                }

                override fun onFailure(msg: String) {
                    //  Log.e("qin","--------onFailure"+msg)
                    callback.onFailure(msg)
                }

                override fun onFinish() {
                    Log.e("qin","--------onFinish")
                    callback.onFinish()
                }
            })
    }
}